package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("api/cart")
public class CartApiController {
    @Autowired
    private CartService cartService;
    //加入购物车
    @RequestMapping("addToCart/{skuId}/{skuNum}")
    public Result addToCart(@PathVariable Long skuId,
                            @PathVariable Long skuNum,
                            HttpServletRequest request){
        //传入skuId skuNum userId
        String userId = AuthContextHolder.getUserId(request);
        //有可能用户为登录
        if (StringUtils.isEmpty(userId)){
            userId =AuthContextHolder.getUserTempId(request);
        }
        cartService.addToCart(skuId,userId,skuNum);
        //默认返回
        return Result.ok();
    }

    //  查看购物车列表
    @GetMapping("cartList")
    public Result cartList(String userId ,String userTempId){
        //  获取购物车列表
        List<CartInfo> cartInfoList = cartService.cartList(userId,userTempId);

        return Result.ok(cartInfoList);
    }
    //  选中状态
    @GetMapping("checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId,
                            @PathVariable Long isChecked,
                            HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)){
            userId=AuthContextHolder.getUserTempId(request);
        }
        cartService.checkCart(skuId,isChecked,userId);
        return Result.ok();
    }

    //      /api/cart/deleteCart/{skuId}
    @DeleteMapping("deleteCart/{skuId}")
        public Result deleteCart(@PathVariable Long skuId,
                                 HttpServletRequest request)
    {
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)){
            userId=AuthContextHolder.getUserTempId(request);
        }

        cartService.deleteCart(skuId,userId);

        return Result.ok();
    }

  //  /api/cart/getCartCheckedList/{userId}
    //获取选中状态的购物车列表
    @GetMapping("getCartCheckedList/{userId}")
    public Result getCartCheckedList(@PathVariable Long userId){
        //获取购物车项的集合
        List<CartInfo> cartInfoList=cartService.getCartCheckedList(userId);
        return Result.ok(cartInfoList);
    }

}
